package server

import (
	"encoding/hex"
	"gitee.com/yangzx6606/core/pattern"
)

type PacketType int

const (
	PacketTypeConnected   PacketType = 0 // 连接成功
	PacketTypeConnectLost PacketType = 1 // 连接断开
	PacketTypeData        PacketType = 2 // 数据包
)

func (p PacketType) ToString() string {
	switch p {
	case PacketTypeConnected:
		return "连接成功"
	case PacketTypeConnectLost:
		return "连接断开"
	case PacketTypeData:
		return ""
	}
	return "未知"
}

// Session 会话接口
type Session interface {
	pattern.Subject[*Packet]
	Write(packet *Packet) error
	GetKey() any
	GetAddress() string
	SetUserData(d any)
	GetUserData() any
}

// Packet 连接状态也通过该数据包回调
type Packet struct {
	Type    PacketType
	Data    []byte
	Session Session
}

func (p *Packet) ToString() string {
	if p.Type == PacketTypeData {
		return "[" + p.Session.GetAddress() + "]" + hex.EncodeToString(p.Data)
	}
	return "[" + p.Session.GetAddress() + "]" + p.Type.ToString()
}

type AbstractSession struct {
	pattern.AbstractSubject[*Packet]
	userData any
}

func (s *AbstractSession) SetUserData(d any) {
	s.userData = d
}

func (s *AbstractSession) GetUserData() any {
	return s.userData
}

// Server 服务端接口
type Server interface {
	pattern.Subject[*Packet]
	Open() error
	Write(*Packet) error
	Close()
}
